<template>
  <div :class="$style.root">
    <!--    :default-openeds="defaultOpeneds"-->
    <el-menu :default-active="activeMenu" :class="$style.menu" @open="handleOpen" @close="handleClose"
             class="el-menu-vertical-demo" background-color="#FFF" active-text-color="#035BEB" router unique-opened>
      <template v-for="(item, index) of filteredRoutes" :key="index">
        <template v-if="item.children && item.children.length > 0">

<!--          v-if="roleRouteList.some(role => role.urlPath == item.path)"-->
          <el-sub-menu :index="item.path" :route="{ name: item.name }">
            <template #title>
              <el-icon>
                <List/>
              </el-icon>
              <span>{{ item.title }}</span>
            </template>
            <template v-for="(items, indexs) of item.children" :key="indexs">
<!--              v-if="roleRouteList.some(role => role.urlPath == items.path)"-->
              <el-menu-item :index="items.path"
                            :route="{ name: items.name }">
                <template #title>
                  <el-icon>
                    <Menu/>
                  </el-icon>
                  <span>{{ items.title }}</span>
                </template>
              </el-menu-item>
            </template>
          </el-sub-menu>
        </template>
        <template v-else>

<!--          v-if="roleRouteList.some(role => role.urlPath == item.path)"-->
          <el-menu-item :index="item.path" :route="{ name: item.name }">
            <template #title>
              <el-icon>
                <Menu/>
              </el-icon>
              <span>{{ item.title }}</span>
            </template>
          </el-menu-item>
        </template>
      </template>
    </el-menu>
    <div :class="$style.right">
      <Breadcrumb :data="breadcrumbData" style="margin-bottom: 13px"/>
      <div style="height: calc(100%)">
        <router-view/>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import Breadcrumb from '@/components/breadcrumb/index.vue';
import {Back, Menu} from '@element-plus/icons-vue';
import {computed, nextTick, onMounted, ref, watch} from 'vue';
import {useRoute, useRouter, type RouteRecordRaw} from 'vue-router';

const router = useRouter();
const roleRoute = ref(localStorage.getItem('roleRouteList') || '[]'); // 默认为空数组字符串

let roleRouteList = ref([]);

try {
  roleRouteList.value = JSON.parse(roleRoute.value);
} catch (error) {
  console.error("Error parsing roleRouteList from localStorage:", error);
  // 如果解析失败，可以设置默认值或进行其他错误处理
  roleRouteList.value = []; // 设置为空数组或者其他默认值
}


const filterRoutes = (routes: RouteRecordRaw[]) => {
  return routes
      .filter((item) => !item.noMenu) // 过滤掉 noMenu 为 true 的顶级路由
      .map((route) => {
        // 递归处理子路由
        if (route.children) {
          return {
            ...route,
            children: filterRoutes(route.children).sort((a, b) => a.sort - b.sort)
          };
        }
        return route;
      });
};

const routes = filterRoutes(router.options.routes);


const route = useRoute();
const breadcrumbData = ref<string[]>([]);

const filteredRoutesBefo = computed(() => {
  const basePath = route.path.split('/')[1]; // 获取一级路由路径
  console.log(basePath,'basePath')
  return routes.filter((route) => route.path === `/${basePath}`);
});

const filteredRoutes = ref([]); // 初始化 ref 为一个空数组
watch(
    filteredRoutesBefo,
    (newFilteredRoutes, oldFilteredRoutes) => {
      console.log(newFilteredRoutes,'newFilteredRoutes')
      // 检查 newFilteredRoutes 是否是一个数组，并且它的第一个元素有 children 属性
      if (
          Array.isArray(newFilteredRoutes) &&
          newFilteredRoutes[0] &&
          newFilteredRoutes[0].children
      ) {
        filteredRoutes.value = newFilteredRoutes[0].children;
      } else {
        // 如果没有 children 属性，可以设置为空数组或者进行其他处理
        filteredRoutes.value = [];
      }

    },
    {
      immediate: true // 立即执行一次打印操作
    }
);

const defaultActiveString: string =
    localStorage.getItem('defaultActiveString') || '';
const defaultActive = ref(defaultActiveString);
const defaultOpeneds = ref(defaultActiveString.split('-')[0]);

onMounted(() => {
  getBreadcrumb();
});

watch(
    () => route.path,
    async () => {
      await nextTick();
      getBreadcrumb();
    }
);

const activeMenu = computed(() => {
  const router = useRouter();
  const {meta, path} = router.currentRoute.value;
  return path;
});

const getBreadcrumb = () => {
  const list = []
  // roleRouteList.value route.path
  const findParentRoute = (pid, routes) => {
    for (const route of routes) {
      if (route.id == pid) {
        list.unshift(route); // 将找到的父级路由的urlPath添加到list的开头
        if (route.pid) { // 如果还有父级，继续递归查找
          findParentRoute(route.pid, routes);
        }
        break;
      }
    }
  };

  let has = false
  // 遍历角色路由列表，构建面包屑
  roleRouteList.value.forEach(loop => {
    if (loop.urlPath === route.path) {

      list.unshift(loop); // 将当前路由的urlPath添加到list的开头
      if (loop.pid) { // 如果有父级，递归查找
        findParentRoute(loop.pid, roleRouteList.value);
      }
    }
  });

  breadcrumbData.value = list
};


const handleOpen = () => {
};

const handleClose = () => {
};
</script>
<style lang="scss" module>
.root {
  width: 100%;
  height: calc(100% - 120px);
  display: flex;

  .menu {
    width: 200px;
    height: 100%;
    overflow-y: auto;
    background-color: #0050A2;


    :global(.el-menu) {
      background-color: #0050A2 !important;
      color: #000 !important;
    }

    :global(.el-menu-item),
    :global(.el-sub-menu__title) {
      color: #fff !important;
      background-color: #0050A2 !important;

      &:hover {
        color: #fff;
        background-color: #4286cb !important;


      }
    }

    :global(.el-menu-item.is-active) {
      color: #fff !important;
      background: #4286cb !important;
      &:after {
        width: 0;
      }
    }
  }

  .right {
    padding: 5px;
    box-sizing: border-box;
    width: calc(100% - 200px);
    height: 100%;
  }
}
</style>
